package com.outsource.framework.controller;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import com.outsource.framework.domain.Thaoduan;
import com.outsource.framework.domain.Trecord;
import com.outsource.framework.domain.Tuserflow;
import com.outsource.framework.domain.Tyonghu;
import com.outsource.framework.domain.custom.Flow;
import com.outsource.framework.model.services.ThaoduanService;
import com.outsource.framework.model.services.TrecordService;
import com.outsource.framework.model.services.TuserflowService;
import com.outsource.framework.model.services.TyonghuService;
import com.outsource.framework.util.common.Constants;
import com.outsource.framework.util.common.DateUtils;
import com.outsource.framework.util.common.GodGenerator;
import com.outsource.framework.util.common.Response;
import com.outsource.framework.util.partyc.ecaop.flow.FlowClient;
import com.outsource.framework.util.unicom.news.sms.SessionSmsValider;
import com.outsource.framework.util.unicom.news.sms.SmsClient;

@Controller
public class YonghuContrller {

	@Autowired
	TyonghuService service;
	@Autowired
	TuserflowService ufservice;
	@Autowired
	TrecordService rservice;
	@Autowired
	ThaoduanService hservice;
	
	@Autowired
	MessageSource messageSource;
	
	/**
	 * login
	 * @param usermobile
	 * @param password
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/WoWebLogin", method = {RequestMethod.GET,RequestMethod.POST})
	public @ResponseBody Map<String, Object> WoWebLogin(
			@RequestParam("usermobile") String usermobile,
			@RequestParam("password") String password,
			@RequestParam("mac") String mac,
			@RequestParam("type") String type,
			HttpServletRequest request) {
		Tyonghu user_requestParam = new Tyonghu(usermobile,password);
		Tyonghu responseEntry = service.login(user_requestParam);
		String responseCode = getMessages("lable.code.success");
		String responseMessages = getMessages("lable.success");
		DecimalFormat df = new DecimalFormat("####.##");
		Flow flow = null;
		if(responseEntry!=null){
			if(responseEntry.getStatus()!=null&&"0".equals(responseEntry.getStatus())){
				responseCode = getMessages("lable.code.error");
				responseMessages = getMessages("lable.error.stop");
			}else{
				flow = new Flow();
				//String updates = String.valueOf(DateUtils.getUpDay());
				String dates = String.valueOf(DateUtils.getDay());
				String month = String.valueOf(DateUtils.getMonth());
				String minmoth = String.valueOf(DateUtils.getMinMonth());
				if(minmoth.equals(dates)){
					month = String.valueOf(DateUtils.getUpMonth());
					dates = String.valueOf(DateUtils.getMaxMonth());
				}
				Tuserflow userflow = ufservice.getByflows(usermobile, month, dates);
				if(userflow!=null){
					Double total = Double.parseDouble(userflow.getTotalflow());
					Double resid = Double.parseDouble(userflow.getUsedflow());
					flow.setTolalflow((StringUtils.isNotBlank(userflow.getTotalflow())?userflow.getTotalflow():"0"));
					flow.setResidualflow(df.format((total - resid))+"");
				}else{
					flow.setTolalflow("0");
					flow.setResidualflow("0");
				}
			}
		}else{
			responseCode = getMessages("lable.code.error.no");
			responseMessages = getMessages("lable.login.error");
		}
		Trecord entity = new Trecord(usermobile, new Date(), "login", Integer.parseInt(type), mac);
		rservice.save(entity);
		Response response = new Response();
		Map<String, Object> responsemap = response.getResponse(responseCode, responseMessages, flow);
		return responsemap;
	}

	/**
	 * logout
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/WoWebLogout", method = {RequestMethod.GET,RequestMethod.POST})
	public @ResponseBody Map<String, Object> WoWebLogout(
			@RequestParam("usermobile") String usermobile, 
			HttpServletRequest request) {
		String responseCode = getMessages("lable.code.success");
		String responseMessages = getMessages("lable.success");
		request.getSession().invalidate();
		Trecord entity = new Trecord(usermobile, new Date(), "logout", null, null);
		rservice.save(entity);
		Response response = new Response();
		Map<String, Object> responsemap = response.getResponse(responseCode, responseMessages, null);
		return responsemap;
	}
	
	/**
	 * regist
	 * @param usermobile
	 * @param custompwd
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/WoWebRegist",method = {RequestMethod.GET,RequestMethod.POST})
	public @ResponseBody Map<String, Object> WoWebRegist(
			@RequestParam("usermobile") String usermobile,
			@RequestParam("custompwd") String custompwd,
			HttpServletRequest request){
		Response response = new Response();
		Tyonghu user_requestParam = new Tyonghu();
		Tyonghu responseEntry = null;
		String responseCode = getMessages("lable.code.success");
		String responseMessages = null;
		String password = "";
		if(StringUtils.isNotBlank(usermobile)){
			Tyonghu th = service.getByYh(usermobile);
			if(th!=null){
				responseCode = getMessages("lable.code.error.ct");
				responseMessages = getMessages("lable.error.regist1");
			}else{
				if(StringUtils.isNotBlank(usermobile)){
					user_requestParam.setMobile(usermobile);
				}
				if(StringUtils.isNotBlank(custompwd)){
					password = custompwd;
					responseMessages = getMessages("lable.success");
				}else{
					password = GodGenerator.getRandomPassword();
					SmsClient smcClient = new SmsClient();
					try {
						smcClient.sendSms(usermobile, getMessages("lable.regist.vcode") + password);
					} catch (Exception e) {
						// TODO: handle exception
					}
					responseMessages = getMessages("lable.vcode.message1");
				}
				Thaoduan hresponseEntry = hservice.findByAttribution(usermobile);
				if(hresponseEntry!=null){
					user_requestParam.setProvince(hresponseEntry.getProvince());
					user_requestParam.setCity(hresponseEntry.getCity());
				}
				user_requestParam.setPassword(password);
				user_requestParam.setCreatetime(new Date());
				responseEntry = service.save(user_requestParam);
				
				FlowClient fc = new FlowClient();
				Tuserflow entity = fc.responseFlow(usermobile);
				if(entity!=null)
					ufservice.save(entity);
				else
					System.out.println("respcode:::::respdesc:::::: flow interface error");
			}
			Trecord entity1 = new Trecord(usermobile, new Date(), "regist", null, null);
			rservice.save(entity1);
		}else{
			responseCode = getMessages("lable.code.error.ct");
			responseMessages = getMessages("lable.vcode.message7");
		}
		Map<String, Object> responsemap = response.getResponse(responseCode, responseMessages, null);
		return responsemap;
	}
	
	/**
	 * sendmsg
	 * @param usermobile
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/WoWebSendMsg",method = RequestMethod.GET)
	public @ResponseBody Map<String, Object> WoWebSendMsg(
			@RequestParam("usermobile") String usermobile,
			@RequestParam("sendtype") String sendtype,
			HttpServletRequest request){
		String responseCode = null;
		String responseMessages = null;
		SmsClient smcClient = new SmsClient();
		if(StringUtils.isNotBlank(usermobile)){
			if(StringUtils.isNotBlank(sendtype)&&"0".equals(sendtype)){
				SessionSmsValider sms = (SessionSmsValider) WebUtils.getSessionAttribute(request, Constants.FRONT_SESSION_SMS_LOGIN);	
				if (sms == null){
					sms = new SessionSmsValider(usermobile);
					WebUtils.setSessionAttribute(request, Constants.FRONT_SESSION_SMS_LOGIN, sms);
				} else{
					sms.setMobile(usermobile);
				}
				String msg = sms.send(smcClient);
				if(msg==null){
					responseCode = getMessages("lable.code.success");
					responseMessages = getMessages("lable.vcode.message");
				}else{
					responseCode = getMessages("lable.code.error");
					responseMessages = msg;
				}
			}
		}else{
			responseCode = getMessages("lable.code.error.ct");
			responseMessages = getMessages("lable.vcode.message7");
		}
		Response response = new Response();
		Map<String, Object> responsemap = response.getResponse(responseCode, responseMessages, null);
		return responsemap;
	}
	
	/**
	 * send sms validate
	 * @param usermobile
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/WoWebSmsCode",method = RequestMethod.GET)
	public @ResponseBody Map<String, Object> WoWebSmsCode(
			@RequestParam("usermobile") String usermobile,
			@RequestParam("smscode") String smsCode,
			HttpServletRequest request){
		String responseCode = null;
		String responseMessages = null;
		if(StringUtils.isNotBlank(usermobile)){
			SessionSmsValider sms = (SessionSmsValider)WebUtils.getSessionAttribute(request, Constants.FRONT_SESSION_SMS_LOGIN);
			if(sms!=null){
				boolean smsvd = sms.isValid(usermobile, smsCode);
				if(smsvd){
					responseCode = getMessages("lable.code.success");
					responseMessages = getMessages("lable.vcode.message5");
				}else{
					responseCode = getMessages("lable.code.error.ct");
					responseMessages = getMessages("lable.vcode.message4");
				}
			}else{
				responseCode = getMessages("lable.code.error.ct");
				responseMessages = getMessages("lable.vcode.message6");
			}
		}else{
			responseCode = getMessages("lable.code.error.ct");
			responseMessages = getMessages("lable.vcode.message7");
		}
		Response response = new Response();
		Map<String, Object> responsemap = response.getResponse(responseCode, responseMessages, null);
		return responsemap;
	}
	
	/**
	 * forget password
	 * @param usermobile
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/WoWebForgetPwd",method = {RequestMethod.GET,RequestMethod.POST})
	public @ResponseBody Map<String, Object> WoWebForgetPwd(
			@RequestParam("usermobile") String usermobile,
			HttpServletRequest request){
		String responseCode = getMessages("lable.code.success");
		String responseMessages = getMessages("lable.success");
		if(StringUtils.isNotBlank(usermobile)){
			String password = service.getByPasswords(usermobile);
			if(StringUtils.isNotBlank(password)){
				SmsClient smcClient = new SmsClient();
				try {
					responseMessages = getMessages("lable.vcode.message1");
					smcClient.sendSms(usermobile, getMessages("lable.vcode.password") + password);
				} catch (Exception e) {
					// TODO: handle exception
					responseMessages = getMessages("lable.vcode.message2");
				}
			}else{
				responseCode = getMessages("lable.code.error.notfind");
				responseMessages = getMessages("lable.error.regist");
			}
		}else{
			responseCode = getMessages("lable.code.error.ct");
			responseMessages = getMessages("lable.vcode.message7");
		}
		Response response = new Response();
		Map<String, Object> responsemap = response.getResponse(responseCode, responseMessages, null);
		return responsemap;
	}
	
	/**
	 * update password
	 * @param usermobile
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/WoWebUpdatePwd",method = {RequestMethod.GET,RequestMethod.POST})
	public @ResponseBody Map<String, Object> WoWebUpdatePwd(
			@RequestParam("usermobile") String usermobile,
			@RequestParam("oldpwd") String oldpwd,
			@RequestParam("newpwd") String newpwd,
			HttpServletRequest request){
		String responseCode = getMessages("lable.code.success");
		String responseMessages = getMessages("lable.success");
		if(StringUtils.isNotBlank(usermobile)){
			Tyonghu th = service.getByYh(usermobile);
			if(th!=null){
				if(StringUtils.isNotEmpty(oldpwd)&&!th.getPassword().equals(oldpwd)){
					responseCode = getMessages("lable.code.error.no");
					responseMessages = getMessages("lable.error.pwd");
				}else{
					th.setPassword(newpwd);
					th.setUpdatetime(new Date());
					service.update(th);
					responseMessages = getMessages("lable.vcode.message3");
				}
			}else{
				responseCode = getMessages("lable.code.error.notfind");
				responseMessages = getMessages("lable.error.regist");
			}
			Trecord entity1 = new Trecord(usermobile, new Date(), "uppwd", null, null);
			rservice.save(entity1);
		}else{
			responseCode = getMessages("lable.code.error.ct");
			responseMessages = getMessages("lable.vcode.message7");
		}
		Response response = new Response();
		Map<String, Object> responsemap = response.getResponse(responseCode, responseMessages, null);
		return responsemap;
	}
	
	/**
	 * get user flow(one)
	 * @param usermobile
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/WoWebFlow", method = {RequestMethod.GET,RequestMethod.POST})
	public @ResponseBody Map<String, Object> WoWebLogin(
			@RequestParam("usermobile") String usermobile,
			HttpServletRequest request) {
		String responseCode = getMessages("lable.code.success");
		String responseMessages = getMessages("lable.success");
		Flow flow = new Flow();
		if(StringUtils.isNotBlank(usermobile)){
			String dates = String.valueOf(DateUtils.getDay());
			String month = String.valueOf(DateUtils.getMonth());
			String minmoth = String.valueOf(DateUtils.getMinMonth());
			if(minmoth.equals(dates)){
				month = String.valueOf(DateUtils.getUpMonth());
				dates = String.valueOf(DateUtils.getMaxMonth());
			}
			DecimalFormat df = new DecimalFormat("####.##");
			Tyonghu th = service.getByYh(usermobile);
			if(th==null){
				//find user if null send password & save
				String password = GodGenerator.getRandomPassword();
				SmsClient smcClient = new SmsClient();
				try {
					smcClient.sendSms(usermobile, getMessages("lable.regist.vcode") + password);
				} catch (Exception e) {
					// TODO: handle exception
				}
				//save
				Tyonghu user_requestParam = new Tyonghu();
				user_requestParam.setMobile(usermobile);
				user_requestParam.setPassword(password);
				user_requestParam.setCreatetime(new Date());
				service.save(user_requestParam);
				//select flow interface 
				FlowClient fc = new FlowClient();
				Tuserflow entity = fc.responseFlow(usermobile);
				
				if(entity!=null){
					//save data
					Tuserflow userflow1 = ufservice.save(entity);//ufservice.getByflows(usermobile, month, dates);
					Double total = Double.parseDouble(userflow1.getTotalflow());
					Double resid = Double.parseDouble(userflow1.getUsedflow());
					flow.setTolalflow((StringUtils.isNotBlank(userflow1.getTotalflow())?userflow1.getTotalflow():"0"));
					flow.setResidualflow(df.format((total - resid))+"");
				}else{
					System.out.println("respcode:::::respdesc:::::: flow interface error");
					flow.setTolalflow("0");
					flow.setResidualflow("0");
				}
			}else{
				Tuserflow userflow = ufservice.getByflows(usermobile, month, dates);
				System.out.println(dates);
				if(userflow!=null){
					Double total = Double.parseDouble(userflow.getTotalflow());
					Double resid = Double.parseDouble(userflow.getUsedflow());
					flow.setTolalflow((StringUtils.isNotBlank(userflow.getTotalflow())?userflow.getTotalflow():"0"));
					flow.setResidualflow(df.format((total - resid))+"");
				}else{
					flow.setTolalflow("0");
					flow.setResidualflow("0");
				}
			}
			Trecord entity1 = new Trecord(usermobile, new Date(), "flow", null, null);
			rservice.save(entity1);
		}else{
			responseCode = getMessages("lable.code.error.ct");
			responseMessages = getMessages("lable.vcode.message7");
		}
		Response response = new Response();
		Map<String, Object> responsemap = response.getResponse(responseCode, responseMessages, flow);
		return responsemap;
	}
	
	/**
	 * get zh.properties content
	 * @param code
	 * @return
	 */
	public String getMessages(String code){
		return messageSource.getMessage(code, null,Locale.SIMPLIFIED_CHINESE);
	}
	
}
